<?php
/**
 * 应用仓库
 * @author wangwx 2015-5-13
 */

namespace common\repositories\common;

use common\entities\common\MyscrmAuthorizeTypeEntity;
use common\repositories\BaseRepository;
use common\entities\common\MyscrmApplicationEntity;
use yii\helpers\ArrayHelper;

class MyscrmApplicationRepository extends BaseRepository {
	
	/**
	 * 根据应用id,获取应用对象
	 * @param string $applicationId 应用id
	 * @return MyscrmApplicationEntity
	 */
	public static function getApplicationByApplicationId($applicationId) {
		return MyscrmApplicationEntity::getApplicationByApplicationId($applicationId);
	}

    /**
     * 获取所有应用
     * @return array|MyscrmApplicationEntity[]
     * @param bool $includeUnAuth 是否包含未授权的应用
     */
    public function getAll($includeUnAuth = true)
    {
        $authTypeList = MyscrmAuthorizeTypeEntity::find()->all();
        $applicationIdList = ArrayHelper::getColumn($authTypeList, 'ApplicationId');
        $query = MyscrmApplicationEntity::find()
            ->where(['ApplicationId' => $applicationIdList])
            ->orderBy([
                'OrderBy' => SORT_ASC,
            ]);

        if ($includeUnAuth == false) {
            $query->andWhere([
                'IsUnAuth' => 0,
            ]);
        }

        return $query->all();
    }

    /**
     * 获取所有应用
     * @return array|MyscrmApplicationEntity[]
     */
    public function getAllApplication()
    {
        return MyscrmApplicationEntity::find()
            ->orderBy([
                'OrderBy' => SORT_ASC
            ])
            ->all();
    }

    public function getAppCodeById($id)
    {
        return MyscrmApplicationEntity::find()
            ->select(['UniqueName'])
            ->where(['ApplicationId' => $id])
            ->scalar();
    }

    /**
     * 获取额外的应用，目前只有小蜜蜂
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getExtraApplications()
    {
        $query = MyscrmApplicationEntity::find()
            ->where([
                'IsUnAuth' => 0                ,
                'UniqueName' => [MyscrmApplicationEntity::XMF],
            ])
            ->orderBy([
                'OrderBy' => SORT_ASC,
            ]);

        return $query->all();
    }
}

